package com.das.mechanic_alone.mvp.presenter.maintain;

import com.das.mechanic_alone.mvp.contract.maintain.X3MainNewTainContract;
import com.das.mechanic_base.base.X3BaseCallModel;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.alone.AloneTitleBean;
import com.das.mechanic_base.bean.alone.UnCompleteBean;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.common.UploadVideoBean;
import com.das.mechanic_base.bean.create.ServiceInfoBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.greendao.AloneServiceNewBean;
import com.das.mechanic_base.bean.live.FetchLiveBean;
import com.das.mechanic_base.bean.live.LiveCarListBean;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.bean.main.UpadateReceBean;
import com.das.mechanic_base.bean.main.UpdateReceiveCarBean;
import com.das.mechanic_base.bean.maintain.AdvanceTimeBean;
import com.das.mechanic_base.bean.maintain.CancelWorkBean;
import com.das.mechanic_base.bean.maintain.WorkBaseHeaderBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3LogUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class X3MainNewTainPresenter extends X3BasePresenter<X3MainNewTainContract.View> implements X3MainNewTainContract.Presenter {

    private Disposable disposable;

    @Override
    public void getAllCheck() {
        if (mView == null){
            return;
        }
        NetWorkHttp.getApi().getWorkBaseHeader(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<WorkBaseHeaderBean>() {
                    @Override
                    protected void onDone(WorkBaseHeaderBean headerBean) {
                        if (headerBean == null) {
                            return;
                        }
                        mView.getWorkBaseHeaderInfo(headerBean);
                        checkStatus(headerBean.getWorkBaseStatus());
                        getTechnicCheck();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 根据施工状态 判断
     * @param status
     */
    private void checkStatus(long status) {
        switch ((int) status) {
            case 0:
                // 未开始工单
                mView.showAdvanceWork();
//                // 先查询是否可以提前施工
//                NetWorkHttp.getApi().obtainValidAdvance(mView.providerWorkBaseId())
//                        .compose(RxSchedulersHelper.defaultComposeRequest())
//                        .subscribe(new HttpCallBack<Boolean>() {
//                            @Override
//                            protected void onDone(Boolean o) {
//                                if (o) {
//                                    // true 可以提前施工
//                                    mView.showAdvanceWork();
//                                }else {
//                                    // false 不可以提前施工 所以必须和之前一样
//                                    mView.showPointDialog("系统发现当前工位在该时间之前还有其它施工单，因此无法提前到现在开始，请您先查看该施工单～");
//                                }
//                            }
//
//                            @Override
//                            protected String LoadingMessage() {
//                                return null;
//                            }
//
//                            @Override
//                            protected void showError(String error) {
//
//                            }
//                        });
                break;
            default:
                break;
        }
    }

    /**
     * 校验技师是否串工位
     */
    @Override
    public void obtainWorkBase() {
        NetWorkHttp.getApi().obtainWorkBaseValidate(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.<X3BaseCallModel<Boolean>>defaultComposeRequest())
                .subscribe(new HttpCallBack<Boolean>() {
                    @Override
                    protected void onDone(Boolean isInTo) {
                        mView.setContainMe(isInTo);
                        getAllCheck();

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void completeWorkForce() {
        NetWorkHttp.getApi().completeWorkBaseForce(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.completeWorkForceSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void startStoreLiveRoom() {
        disposable = Observable.interval(5,5, TimeUnit.SECONDS)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.<Long>defaultComposeRequest())
                .doOnNext(aLong -> {
                    //Log.e("SSSS", "第几次轮训任务:" + aLong);
                    // 轮询任务
                    getLiveNum();
                }).subscribe();
    }

    /**
     * 获取当前正在直播的数量
     */
    private void getLiveNum() {
        NetWorkHttp.getApi().listStoreLiveRoom()
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new Observer<X3BaseCallModel<List<LiveCarListBean>>>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable disposable) {

                    }

                    @Override
                    public void onNext(@NotNull X3BaseCallModel<List<LiveCarListBean>> listBaseCallModel) {
                        long status = listBaseCallModel.status;
                        mView.getStoreLiveRoomSuccess(0);
                        if (status == 0) {
                            List<LiveCarListBean> liveCarListBeans = listBaseCallModel.data;
                            if (X3StringUtils.isListEmpty(liveCarListBeans)) {
                                mView.getStoreLiveRoomSuccess(0);
                                return;
                            }
                            mView.getStoreLiveRoomSuccess(liveCarListBeans.size());
                        }
                    }

                    @Override
                    public void onError(@NotNull Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void endStoreLiveRoom() {
        if (disposable == null || disposable.isDisposed()) {
            return;
        }
        disposable.dispose();
    }

    @Override
    public void getCancelWork() {
        NetWorkHttp.getApi().obtainListReceive(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CancelWorkBean>>() {
                    @Override
                    protected void onDone(List<CancelWorkBean> cancelWorkBeans) {
                        mView.getCancelWorkList(cancelWorkBeans);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                    }
                });
    }

    @Override
    public void affirmCancelWork(List<CancelWorkBean> mList, boolean isOne) {
        List<Long> idList = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            idList.add(mList.get(i).getReceiveVariantId());
        }

        NetWorkHttp.getApi().obtainCancelWork(idList)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.finishCurrent();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mView.showFaild(error+"");
                    }
                });
    }

    @Override
    public void updateAdavancService() {
        NetWorkHttp.getApi().obtainUpdateStartTime(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<AdvanceTimeBean>() {
                    @Override
                    protected void onDone(AdvanceTimeBean advanceTimeBean) {
                        mView.updateAfterWork(advanceTimeBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    public void showErrorStatus(int status) {
                        if (1101 == status) {
                            getAllCheck();
                        }
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    public void getTechnicCheck() {
        /**
         * 当前只有单人精检
         */
        NetWorkHttp.getApi().obtainCheck(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<AloneTitleBean>>() {
                    @Override
                    protected void onDone(List<AloneTitleBean> aloneTitleBeans) {
                        if (aloneTitleBeans != null) {
                            mView.getAlone(aloneTitleBeans);
                        }
                    }

                    @Override
                    public void showErrorStatus(int status) {
                        super.showErrorStatus(status);
                        mView.showErrorStatus(status);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        if (error != null && !"".equals(error)) {
                            mView.navigateTain(error);
                        }
                    }
                });
    }

    @Override
    public void getReceiveBase(long receiveId,boolean isShow) {
        if (receiveId == 0) {
            return;
        }
        NetWorkHttp.getApi().getReceiveBase(receiveId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<HomeMainCarBean>() {
                    @Override
                    protected void onDone(HomeMainCarBean mainCarBean) {
                        mView.getReceiveBase(mainCarBean,isShow);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void completeWorkBase(long id, UpdateReceiveCarBean carBean,boolean isUpdate) {
        NetWorkHttp.getApi().obtainCompleteWork(id)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.onCompleteWork();
                        if (isUpdate) {
                            updateCarBean(carBean);
                            return;
                        }
                        mView.jumpComplete();

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mView.resetButton();
                    }
                });
    }

    private void updateCarBean(UpdateReceiveCarBean carBean) {
        NetWorkHttp.getApi().updateReceiveCar(carBean)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<UpadateReceBean>() {
                    @Override
                    protected void onDone(UpadateReceBean upadateReceBean) {
                        upadateReceBean.setFirstName(carBean.getFirstName());
                        mView.updateReceiveSuccess(upadateReceBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mView.resetButton();
                    }
                });
    }

    @Override
    public void uploadCarPic(long carId, String imgPath, String carNum) {
        File imgFile = new File(imgPath);
        if (!imgFile.exists()) {
            return;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);
        try {
            String  filename = URLEncoder.encode(imgFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            NetWorkHttp.getApi().createCarPic(carId,carNum,fileBody)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<CarPicAndColorBean>() {
                        @Override
                        protected void onDone(CarPicAndColorBean colorBean) {
                            mView.uploadCarPicSuccess(colorBean);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            mView.uploadCarPicSuccess(null);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void requestVin(File carVin) {
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), carVin);
            String  filename = URLEncoder.encode(carVin.getName(), "UTF-8");
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestBody);
            NetWorkHttp.getApi().vinRecognition(body)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<String>() {
                        @Override
                        protected void onDone(String vin) {
                            mView.getVin(vin);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void updateCarProductionAndMiles(Map<String, Object> map, UpdateReceiveCarBean carBean) {
        NetWorkHttp.getApi().updateCarProductionAndMiles(map)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<AloneServiceListBean>() {
                    @Override
                    protected void onDone(AloneServiceListBean serviceListBean) {
                        completeWorkBase(mView.providerWorkBaseId(),carBean,true);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mView.resetButton();
                    }
                });
    }

    @Override
    public void uploadHeaderAws(File imgFile) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);
        try {
            String  filename = URLEncoder.encode(imgFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "车主头像"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            NetWorkHttp.getApi().uploadFileAws(map,fileBody,new HashMap<>())
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            if (awsFileBean == null){
                                return;
                            }
                            updateCarOwnerUserPortrait(mView.providerCarId(),awsFileBean.id);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void getDetectionServiceList() {
        NetWorkHttp.getApi().getTouchServiceList(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<AloneServiceNewBean>>() {
                    @Override
                    protected void onDone(List<AloneServiceNewBean> mList) {
                        if (X3StringUtils.isListEmpty(mList)) {
                            mView.getSaveService(0);
                            return;
                        }
                        mView.getSaveService(mList.size());
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void generateLiveInfoOnLocal(long carId, boolean isCarOwnerRequired, long workBaseId) {
        NetWorkHttp.getApi().generateLiveInfoOnLocal(carId,isCarOwnerRequired,workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<FetchLiveBean>() {
                    @Override
                    protected void onDone(FetchLiveBean fetchLiveBean) {
                        if(fetchLiveBean != null){
                            mView.getLiveInfoSuccess(fetchLiveBean);
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }


    public void updateCarOwnerUserPortrait(long carId, long resourceId) {
        NetWorkHttp.getApi().updateCarOwnerUserPortrait(carId, resourceId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<String>() {
                    @Override
                    protected void onDone(String str) {
                        //上传成功
                        X3LogUtils.e("头像保存到服务器成功");
                        mView.completeSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void listLiveUploadVideo(long workBaseId) {

        NetWorkHttp.getApi().listLiveUploadVideo(workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<UploadVideoBean>>() {
                    @Override
                    protected void onDone(List<UploadVideoBean> uploadVideoBean) {
                        mView.getUploadVideoSuccess(uploadVideoBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void getUnCompleteList(long workBaseId) {
        NetWorkHttp.getApi().getUnCompleteQuestionList(workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<UnCompleteBean>>() {
                    @Override
                    protected void onDone(List<UnCompleteBean> unCompleteBeans) {
                        mView.getUnCompleteListSuccess(unCompleteBeans);
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    @Override
    public void getWorkBase() {
        NetWorkHttp.getApi().getWorkBase(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<ServiceInfoBean.WorkBaseBean>() {
                    @Override
                    protected void onDone(ServiceInfoBean.WorkBaseBean workBaseBean) {
                        mView.getWorkBaseSuccess(workBaseBean);
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

}
